package org.wanho.servlet;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.wanho.entity.User;
import org.wanho.service.UserService;
import org.wanho.service.impl.UserServiceImpl;
import org.wanho.vo.AjaxResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author：汤小洋
 * Date：2024-12-03 14:57
 * Description：<描述>
 */
@WebServlet("/addUser")
public class AddUserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();


    @SneakyThrows
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        Integer age = Integer.parseInt(req.getParameter("age"));
        String sex = req.getParameter("sex");
        Double height = Double.parseDouble(req.getParameter("height"));
        String birthdayStr = req.getParameter("birthday");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = sdf.parse(birthdayStr);
        User user = new User(null, name, pwd, age, sex, height, birthday);

        // 添加到数据库
        userService.add(user);

        // 响应结果
        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();

        AjaxResult result = new AjaxResult();
        result.setStatus(200);
        result.setMsg("添加成功");
        out.print(JSON.toJSONString(result));
        out.close();
    }
}
